package com.ywxx.dyhelper.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.widget.Toast;


import com.ywxx.dyhelper.BuildConfig;
import com.ywxx.dyhelper.R;
import com.ywxx.dyhelper.base.BaseAcitivity;
import com.ywxx.dyhelper.model.ResponseModel;
import com.ywxx.dyhelper.utils.ConstAPI;
import com.ywxx.dyhelper.utils.ConstValues;
import com.ywxx.dyhelper.utils.HttpUtils;
import com.ywxx.dyhelper.utils.ParamsHelper;

import java.util.ArrayList;

public class WelcomeActivity extends BaseAcitivity
{

    private final int mRequestCode = 100;//权限请求码

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weclome);
        ConstValues.getInstance().InitParams(this);

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M)//|| BuildConfig.DEBUG == true
        {
            ConstValues.getInstance().InitParams(this);
            InitUI();
        } else
        {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("温馨提示");
            dialog.setMessage("该手机安卓版本过低，无法使用(需要安卓7.0系统)...");
            dialog.setPositiveButton("退出", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialogInterface, int i)
                {
                    WelcomeActivity.this.finish();
                }
            });
            dialog.show();
        }
    }

    /**
     * 权限获取
     */
    @Override
    protected void InitUI()
    {
        //需要申请的动态权限
        ArrayList<String> permissions = new ArrayList<>();
        permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        permissions.add(Manifest.permission.READ_PHONE_STATE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            permissions.add(Manifest.permission.WRITE_SETTINGS);
        }

        ArrayList<String> mPermissionList = new ArrayList<>();
        //逐个判断你要的权限是否已经通过
        for (String permission : permissions)
        {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED)
            {
                mPermissionList.add(permission);//添加还未授予的权限
            }
        }
        //申请权限
        if (mPermissionList.size() > 0)
        {   //有权限没有通过，需要申请
            ActivityCompat.requestPermissions(this, permissions.toArray(new String[]{}), mRequestCode);
        } else
        {
            //说明权限都已经通过，可以做你想做的事情去
            if (BuildConfig.DEBUG == true)
                GoToNext();
            else
                GoToMain();
        }
    }

    @Override
    protected void DataToUI()
    {

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDismiss = false;//有权限没有通过
        String msg = "";
        if (mRequestCode == requestCode)
        {
            for (int i = 0; i < grantResults.length; i++)
            {
                if (grantResults[i] == -1 && permissions[i].equals(Manifest.permission.WRITE_SETTINGS) == false)
                {
                    hasPermissionDismiss = true;
                    if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE))
                        msg += "存储访问权限\r\n";
                    if (permissions[i].equals(Manifest.permission.CAMERA))
                        msg += "相机访问权限\r\n";
                    if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION))
                        msg += "位置访问权限\r\n";
                    //                    if (permissions[i].equals(Manifest.permission.ACCESS_BACKGROUND_LOCATION))
                    //                        msg += "位置后台访问权限\r\n";
                    if (permissions[i].equals(Manifest.permission.READ_PHONE_STATE))
                        msg += "电话访问权限\r\n";
                    if (permissions[i].equals(Manifest.permission.WRITE_CALENDAR))
                        msg += "访问日程信息权限\r\n";
                    if (permissions[i].equals(Manifest.permission.WRITE_SETTINGS))
                        msg += "系统设置权限\r\n";
                }
            }
            //如果有权限没有被允许
            if (hasPermissionDismiss)
            {

                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                dialog.setMessage("已禁用权限，请手动授予以下权限：" + msg);
                dialog.setPositiveButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i)
                    {
                        dialogInterface.dismiss();
                    }
                });
                dialog.setNegativeButton("马上设置", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i)
                    {
                        Uri packageURI = Uri.parse("package:" + BuildConfig.APPLICATION_ID);
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        startActivity(intent);
                    }
                });
                dialog.show();
            } else
            {
                //全部权限通过，可以进行下一步操作。。。
                GoToNext();
            }
        }
    }

    private void GoToNext()
    {
        ParamsHelper params = new ParamsHelper(ConstAPI.启动检验);
        params.Add("deviceno", ConstValues.getIMEI(this));
        params.Add("appversion", BuildConfig.VERSION_NAME);
        params.Add("dyversion", ConstValues.getDyAPPVer(this));

        new HttpUtils(params)
        {
            @Override
            public void onHttpResult(ResponseModel response)
            {
                if (response.status == 1)
                {
                    new Handler().postDelayed(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            GoToMain();
                        }
                    }, BuildConfig.DEBUG ? 1000 : 2000);
                } else
                {
                    Toast.makeText(WelcomeActivity.this, response.msg, Toast.LENGTH_LONG).show();
                    startActivity(new Intent(WelcomeActivity.this, AuthorizationActivity.class));
                    finish();
                }
            }
        };
    }

    private void GoToMain()
    {
        //初始化根目录
        ConstValues.getInstance().InittPath(this);

        startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
        finish();

    }
}